﻿using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Qins.PluginInterface;
using Qins.PluginInterface.Model;
using Qins.PluginLoader;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace UniversalQin
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Control.CustomWindow
    {
        public MainWindow()
        {
            this.Name = "UniversalQin";
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                string pluginsPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\plugins";


                PluginsLoader.Instance.load(pluginsPath);
                PluginsLoader pl = PluginsLoader.Instance;
                pl.PluginUpdated += new PluginsLoader.PluginUpdateHandler(PluginCalled);

                

                foreach (var com in PluginsLoader.Instance.pluginComs)
                {
                    if (com.Value.AutoRun == true)
                    {
                        com.Value.Execute(null);
                    }
                }

                InitCoreWebView2();
                vw2.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
            }
            catch (Exception ex)
            {
                //这里需要日志记录问题
                throw;
            }
        }

        private async void InitCoreWebView2()
        {
            if (vw2.CoreWebView2 == null)
            {
                await vw2.EnsureCoreWebView2Async();
            }
            //vw2.CoreWebView2.Settings.AreDevToolsEnabled = false;

            //vw2.EnsureCoreWebView2Async();
            //vw2.WebMessageReceived += (s, e) =>
            //{
            //    MessageBox.Show(e.WebMessageAsJson);
            //    vw2.CoreWebView2.PostWebMessageAsString("hello world");
            //};
            vw2.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;

        }

        //这是chrome方式的 有了新的方法
        private void WebView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
        {
            try
            {
                if (vw2 != null && vw2.CoreWebView2 != null)
                {                    
                    //注册csobj脚本c#互操作
                    vw2.CoreWebView2.AddHostObjectToScript("csobj", new WebScript.ScriptCallbackObject());
                    //注册全局变量csobj
                    vw2.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var csobj = window.chrome.webview.hostObjects.csobj;");
                    vw2.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var csobj_sync= window.chrome.webview.hostObjects.sync.csobj;");

                    ////加载页面
                    //string rootPath = Environment.CurrentDirectory;
                    //string filepath = System.IO.Path.Combine(rootPath, "html", "index.html");
                    //string text = System.IO.File.ReadAllText(filepath);
                    //vw2.CoreWebView2.NavigateToString(text);
                }
            }
            catch (Exception ex)
            {

                throw;
            }

        }

        private void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            //e.NewWindow = webView22.CoreWebView2;
            //在第二个webview2上面打开这个新窗口
            if (!newWindowRequested)
            {
                vw2.Source = new Uri(e.Uri.ToString());
                e.Handled = true;//禁止弹窗
            }

        }


        public void Seturl(string url)
        {
            vw2.Source = new Uri(url);
        }
        public void SetWindow(string content)
        {
            try
            {
                SetWindowSetting am = JsonConvert.DeserializeObject<SetWindowSetting>((string)content);
                if (am?.lbtitle != null)
                {
                    lbTitle.Content = am.lbtitle;
                    this.Title = am.lbtitle;
                }
                if (am?.imgtitle != null)
                {
                    this.Icon= new BitmapImage(new Uri(am.imgtitle, UriKind.RelativeOrAbsolute));
                    imgTitle.Source = new BitmapImage(new Uri(am.imgtitle, UriKind.RelativeOrAbsolute));
                }
                if (am?.IsVisible != null)
                {                    
                    if (am.IsVisible == true)
                    {
                        lbTitle.Visibility = Visibility.Visible;
                        imgTitle.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        lbTitle.Visibility = Visibility.Hidden;
                        imgTitle.Visibility = Visibility.Hidden;
                    }
                }
                if (am?.titleEnevt != null)
                {
                    spTitle.MouseUp += SpTitle_MouseUp; ;
                    imgTitle.Tag = am.titleEnevt;
                    //imgUserInfo.MouseUp += ImgUserInfo_MouseUp;
                }
            }
            catch (Exception)
            {
                throw;
            }            
        }

        private void SpTitle_MouseUp(object sender, MouseButtonEventArgs e)
        {
            vw2.Source = new Uri(imgTitle.Tag.ToString());
        }

        public void SetUserInfo(string content)
        {
            try
            {
                UserInfoSetting am = JsonConvert.DeserializeObject<UserInfoSetting>((string)content);
                if (am.lbUserInfo != null)
                    lbUserInfo.Content = am.lbUserInfo;
                if (am.imgUserInfo != null)
                    imgUserInfo.Source = new BitmapImage(new Uri(am.imgUserInfo, UriKind.RelativeOrAbsolute));
                if (am.IsVisible != null)
                {
                    if (am.IsVisible == true)
                    {
                        lbUserInfo.Visibility = Visibility.Visible;
                        imgUserInfo.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        imgUserInfo.Visibility = Visibility.Hidden;
                        lbUserInfo.Visibility = Visibility.Hidden;
                    }                        
                }
                if (am.UserInfoEnevt != null)
                {
                    spUserInfo.MouseUp += SpUserInfo_MouseUp;
                    imgUserInfo.Tag = am.UserInfoEnevt;
                    //imgUserInfo.MouseUp += ImgUserInfo_MouseUp;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public string GetVersion()
        {
            Version version = Assembly.GetExecutingAssembly().GetName().Version;
            string versionString = version.ToString();
            return versionString;
        }

        private void ImgUserInfo_MouseUp(object sender, MouseButtonEventArgs e)
        {
            vw2.Source = new Uri(imgUserInfo.Tag.ToString());
        }
        private void SpUserInfo_MouseUp(object sender, MouseButtonEventArgs e)
        {
            vw2.Source = new Uri(imgUserInfo.Tag.ToString());
        }

        private string PluginCalled(object sender, PluginsLoader.PluginUpdateEventArgs e)
        {
            string reResult = "";
            try
            {
                MessageContent mc = (MessageContent)e.Content;
                if (mc != null)
                {
                    switch (mc.messageType)
                    {
                        case MessageConentTypeEnum.OpenUrl:
                            Seturl(mc.content);
                            break;
                        case MessageConentTypeEnum.SetWindow:
                            SetWindow(mc.content);
                            break;
                        case MessageConentTypeEnum.SetUserInfo:
                            SetUserInfo(mc.content);
                            break;
                        case MessageConentTypeEnum.GetVersion:
                            return GetVersion();
                            break;
                    }
                }
                return reResult;
            }
            catch (Exception)
            {
                throw;
            }
            return reResult;
        }

        private bool newWindowRequested;
        /// <summary>
        /// 是否打开新窗体，默认为false
        /// </summary>
        public bool SetNewWindowRequested { get;set; }
    }
}
